package com.supcalls;

import java.util.concurrent.atomic.AtomicReference;

public class AbaCAS {
    static AtomicReference<String> ref = new AtomicReference<>("A");

    public static void main(String[] args) throws InterruptedException {
        System.out.println("main start...");
        // 获取值 A
        // 这个共享变量被它线程修改过？
        String prev = ref.get();
        other();
        Thread.sleep(1000);
        // 尝试改为 C
        System.out.println("change A->C {}" + ref.compareAndSet(prev, "C"));
    }

    private static void other() throws InterruptedException {
        new Thread(() -> {
            System.out.println("change A->B {}" + ref.compareAndSet(ref.get(), "B"));
        }, "t1").start();
        Thread.sleep(500);
        new Thread(() -> {
            System.out.println("change B->A {}" + ref.compareAndSet(ref.get(), "A"));
        }, "t2").start();
    }
}
